package com.apac.dao;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.apac.bom.AbstractBOM;
import com.apac.bom.User;

public class UserDAO extends AbstractDAO {

	@Override
	public AbstractBOM findByKey(String id) {
		int idx = 0;
		try{
			idx = Integer.valueOf(id);
		}catch(NumberFormatException e){
			idx = 0;
		}
		
		return this.findByKey(idx);
	}
	
	public User findByKey(int id){
		User user = null;
		
		user = em.find(User.class, id);
		
		return user;
	}

	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<AbstractBOM> findAll() {
		List<AbstractBOM> users = null;
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<User> cq = cb.createQuery(User.class);
		Root<User> root = cq.from(User.class);
		cq.select(root);
		TypedQuery tq = em.createQuery(cq);
		users = tq.getResultList();

		return users;
	}

	public AbstractBOM findByUserName(String username) {
		User user = null;

		TypedQuery<User> tq = em.createQuery(
				"select u from User u where u.userName = :username",
				User.class);

		tq.setParameter("username", username);
		user = tq.getSingleResult();
		return user;
	}

	@Override
	public boolean update(AbstractBOM entity) {
		try{
			User user = this.findByKey(((User) entity).getUserIdCode());
			tx.begin();
//			user.setAccountPrivileges(((User) entity).getAccountPrivileges());
//			user.setEmployees(((User) entity).getEmployees());
//			user.setUserAuditTrail(((User) entity).getUserAuditTrail());
//			user.setUserDept(((User) entity).getUserDept());
//			user.setUserFrstName(((User) entity).getUserFrstName());
//			user.setUserLstName(((User) entity).getUserLstName());
//			user.setUserPwd(((User) entity).getUserPwd());
//			user.setUserType(((User) entity).getUserType());
			em.merge((User)entity);
			em.flush();
			em.clear();
			tx.commit();
			
			return true;
		}catch(Exception e){
			tx.rollback();
		}finally{
			em.close();
		}
		return false;
		// TODO Auto-generated method stub
	}

	@Override
	public boolean delete(AbstractBOM entity) {
		
		try{
			User user = this.findByKey(((User) entity).getUserIdCode());
			tx.begin();
			em.remove(user);
			em.flush();
			em.clear();
			tx.commit();
			
			return true;
		}catch(Exception e){
			tx.rollback();
		}finally{
			em.close();
		}
		return false;
		// TODO Auto-generated method stub
	}
}
